<?php

namespace App\V3\V3_1\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\V3\V3_1\Services\SealManageService;
use App\V3\V3_1\Models\SealManageModel;
use App\Helper\Utils\CircleSeal;
use App\V3\V3_1\Models\AdminAddendumModel;
use Illuminate\Validation\Rule;
use OSS\OssClient;

class SealManageController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    /**
     * 添加印章
     */
    public function add(Request $request){

        $admininfo   = AdminAddendumModel::select('is_vip','special_seal')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($admininfo) && in_array($admininfo['is_vip'],[1,2])){

            /* $count = SealManageModel::where(['main_id'=>$this->getMainUserId()])->count();

            if($admininfo['special_seal'] != -1 && $count >= $admininfo['special_seal']){

                return $this->fail('','您创建专用印章，已达到设置数量！');
            } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建专用印章！');
        }

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_name'    => 'required|string',//印章名称
            'company_name' => 'required|string',//公司名称
            'type' => [
                Rule::in([1,2]),
            ]

        ],[
            'seal_name.required'   =>"印章名称，不能为空！",
            'company_name.required'=>"公司名称，不能为空！",
            'type.in'              => '请选择,印章样式！',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        ob_end_clean();
        $name = $data['company_name'];
        $path ='uploads/yz/imgs/' . date("Y") . "-" . date("m") . "-". date("d").'/';
        @mkdir($path,0755,true);
        $filename = uniqid();
        $picpath = $path .$filename;

        $cc = new CircleSeal($name);

        $sealname = $data['seal_name'];
        //相关计量
         /*$leng  = mb_strlen($sealname,'utf8'); //字符串长度

        $nameLeng  = mb_strlen($name,'utf8'); //字符串长度
        if($leng > 8) return $this->fail('',"印章名称字数，不能超过8个！");

        if($nameLeng > 10) return $this->fail('',"公司名称字数，不能超过10个！"); */
        if($data['type']==1){

         $cc->saveImg($picpath.".jpg",$sealname);

        }else{

         $cc->saveEll($picpath.".jpg",$sealname);
        }
        //$cc->saveSquare($picpath.".5.jpg",'王丽');

        //开启事务
       DB::beginTransaction();
        try{
            $fullPath = '/'.$picpath.".jpg";
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client   = $this->ossClient;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            $size = filesize($path);
            @unlink($path);
             $result = saveFileSize(['main_id'=>$this->getMainUserId()], $size,$path);
             if($result['code'] == 1){
                return $this->fail('',$result['msg']);
             }
            //印章
            $dData = $data;
            $dData['created_at']   = time();
            $dData['seal_img']     = config('app.aliyun_oss_bucket_url').$fullPath;
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();
            $res=SealManageService::add($dData);

            DB::commit();//提交事务
            $this->log("添加印章", $dData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加印章');
        }

    }

    /**
     * 删除印章信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//印章id
        ],['ids.required'=>'必要参数，印章主键`id`']);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        
        if($this->getUserId()==$this->getMainUserId()){
            $condition['main_id'] = $this->getMainUserId();
        }else{
            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
        }

        $list = SealManageModel::select('id','seal_img')->where($condition)->whereIn('id',$id_arr)->get()->toArray();

        if(!empty($list)){

            foreach ($list as $k=>$v){

                $id_data[]=$v['id'];
            }
            DB::beginTransaction();
            try {
            $bool = SealManageModel::where($condition)->whereIn('id',$id_data)->delete();;
            if($bool){
                foreach ($list as $k=>$v){
                    //删除oss里的文件
                    $delOssRes=self::delOssFilePath($v['seal_img'], $this->ossClient, $this->getMainUserId());
                    if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                }
                DB::commit();
                $this->log("删除印章", $id_data);
                return $this->success();

            }else{
                return $this->fail('','删除失败');
            }

            } catch (\Exception $e) {
                DB::rollBack();
                return $this->fail('',$e->getMessage());
            }
        }
        return $this->fail('','此印章，不存在！');
    }

    /**
     * 修改印章
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_id' =>'required|integer',//印章id
            'seal_name'      => 'required|string',//印章名称
            'company_name'  => 'required|string',//公司名称
            'type' => [
                Rule::in([1,2]),
            ]

        ],[
            'seal_name.required'   =>"印章名称，不能为空！",
            'company_name.required'=>"公司名称，不能为空！",
            'type.in'              => '请选择,印章样式！',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $info = SealManageService::getSealManageInfo(['id'=> $data['seal_id']]);

        if(empty($info)) return $this->fail('','此印章,不存在！');
        if($data['company_name'] != $info['company_name'] || $data['seal_name'] != $info['seal_name'] || $data['type'] != $info['type']){
            ob_end_clean();
            $name = $data['company_name'];
            $path ='uploads/yz/imgs/' . date("Y") . "-" . date("m") . "-". date("d").'/';
            @mkdir($path,0755,true);
            $filename = uniqid();
            $picpath = $path .$filename;
            $cc = new CircleSeal($name);
            $sealname = $data['seal_name'];
            if($data['type']==1){
                $cc->saveImg($picpath.".jpg",$sealname);
            }else{
                $cc->saveEll($picpath.".jpg",$sealname);
            }
        }else{
            return $this->success();
        }
        //开启事务
        DB::beginTransaction();
        try{
            $fullPath = '/'.$picpath.".jpg";
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client   = $this->ossClient;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            $size = filesize($path);
            @unlink($path);
             $result = saveFileSize(['main_id'=>$this->getMainUserId()], $size,$path);
             if($result['code'] == 1){
             return $this->fail('',$result['msg']);
             }
            $data['seal_img'] = config('app.aliyun_oss_bucket_url').$fullPath;
            //印章
            $updData = $data;

            $condition['id'] = $updData['seal_id'];

            unset($updData['seal_id']);
            $updData['updated_at'] = time();

            $bool = SealManageService::update($condition,$updData);
            if($bool){
                //删除oss里的文件
                $delOssRes=self::delOssFilePath($info['seal_img'], $this->ossClient, $this->getMainUserId());
                if(!empty($delOssRes)) return $this->fail('',$delOssRes);
            }else{
                $this->fail('','修改失败');
            }
            DB::commit();//提交事务
            $this->log("删除印章", $updData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改印章');
        }

    }

    /**
     * 印章信息
     * @param seal_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_id'       =>'required|integer',//印章id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $condition['id'] = $data['seal_id'];    
        $info = SealManageService::getSealManageInfo($condition);
        $this->log("印章信息", $info);
        return $this->success($info);
    }

    /**
     * 印章列表
     */
    public function sealList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ], [
            'page_size.required' => '参数`页面大小`丢失',
            'page_size.integer' => '参数`页面大小`仅能为数字',
            'current_page.required' => '参数`当前页码`丢失',
            'current_page.integer' => '参数`当前页码`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $id_arr = [];
        $seal_id_arr = [];

    if($this->getMainUserId() != 0){
        if($this->getUserId() == $this->getMainUserId()) {
                $condition['main_id'] = $this->getMainUserId();
            }
            else {
                if($this->isShareBillhead()) {

                    $condition['main_id'] = $this->getMainUserId();
                }else {
                    $condition['main_id'] = $this->getMainUserId();
                    $condition['user_id'] = $this->getUserId();
                }
            }
        }else{
            $condition['user_id'] = $this->getUserId();
        }

        $list = SealManageService::getList($condition,$seal_id_arr,$data['page_size'],$data['current_page']);
        $this->log("印章列表", $list);
        return $this->success($list);

    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return "";
            }
    }

}
